#!/usr/bin/env python
# -*- coding: utf-8 -*-
# piwate is PIcasa Web Album Tag Editor

# setdefaultencoding
# 通常は sys インポート後に setdefaultencodingは設定できないよう削除されてしまうため、
# reloadしてから設定する
# ElementTreeはこうしないとuncode文字列を扱えなかった
# stdin,stdout,stderrのencodingもここで再定義すると都度指定がいらなくなって楽だが、
# そうすると getpass がうまく動かない(入力文字列が画面に表示されてしまう)。
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import wsgiref.util
from wsgiref import simple_server
from optparse import OptionParser
import StringIO
from xml.sax.saxutils import quoteattr
import codecs
import os.path

import piwalog
logger = piwalog.logging.getLogger("piwate")
import piwadb

# コマンドプロンプトのエンコードを取得。Windowsでは通常'cp932'である。
import locale
console_encode = locale.getpreferredencoding()

HTML_ENCODE='utf-8'

class HtmlBuf:
    coding = None
    buf = None

    def __init__(self, coding='utf-8'):
        self.coding = coding
        self.buf = StringIO.StringIO()

    def write(self, s):
        self.buf.write(s.encode(self.coding))

class PiwaForm(object):
    db = None
   
    def __init__(self, db) :
        self.db = db

    def __call__(self, environ, start_response) :
        """ dispatch
        """
        appname = wsgiref.util.shift_path_info(environ)
        if appname == 'submit' :
            return self.app_submit(environ, start_response)
        elif appname == '' :
            return self.app_index(environ, start_response)
        else :
            # get content type
            (path, ext) = os.path.splitext(appname)
            ext = ext.lower()
            if ext == '.html' :
                content_type = 'text/html'
            elif ext == '.css' :
                content_type = 'text/css'
            else:
                content_type = 'text/plain'

            # get file
            try :
                fp = codecs.open(appname, "r", encoding=HTML_ENCODE)
                html = HtmlBuf(HTML_ENCODE)
                for line in fp:
                    html.write(line)
            except IOError:
                start_response('404 File not Found', [('Content-type', ext)])
                return '404 File not found. - piwate'
            else :
                start_response('200 OK', [('Content-type', '%s;charset=utf-8'%ext)])
                html.buf.seek(0)
                return html.buf

    def app_index(self, environ, start_response) :
        html = HtmlBuf(HTML_ENCODE)
        html.write(u"""<html>
<head>
<title>piwate<title>
<link rel="stylesheet" type="text/css" href="piwate.css">
</head>
<body>""")
        album_list = db.albumList()
        for album in album_list :
            html.write(u"""
  <table class="frame">
    <tr>
      <td>
        <table class="album">
          <tr>
            <td>
              <a href=%s target="_blank" alt=%s><img src=%s></a>
            </td>
          </tr>
          <tr>
            <td>%s</td>
          </tr>
        </table>
      </td>"""%(quoteattr(album['album_link']),
                quoteattr(album['album_title']),
                quoteattr(album['album_thumbnail']),
                album['album_title']))

            photo_list = db.photoList(album['album_id'])
            html.write(u"""
      <td>
        <form method="POST" action="/submit/%(id)s">
          <input type="hidden" name="guess_charset" value="イ" />
          <table class="photo">"""%({'id':photo['photo_id']}))
            for photo in photo_list:
                html.write(u"""
            <tr>
              <td class="thumbnail">
                <a href=%s target="_blank" alt=%s><img src=%s></a>
              </td>"""%(quoteattr(photo['photo_link']),
                     quoteattr(photo['photo_title']),
                     quoteattr(photo['photo_thumbnail'])))

                tag_list = db.tagList(photo['photo_id'])
                for tag in tag_list:
                    html.write(u"""
              <td>
                <input type="text" id=%s name="photo_tag" value=%s>
              </td>"""%(quoteattr(photo['photo_id']),
                     quoteattr(tag['photo_tag'])))
                
                html.write(u"""
            </tr>""")

            html.write(u"""
          </table>
        </form>
      </td>
    </tr>""")
            html.write(u"""
  </table>
""")
        html.write(u"""
</body>
<html>""")
        start_response('200 OK', [('Content-type', 'text/html;charset=utf-8')])
        html.buf.seek(0)
        return html.buf
                              
    def app_submit(self, environ, start_response) :
        album_id = wsgiref.util.shift_path_info(environ)
        photo_id = wsgiref.util.shift_path_info(environ)


        buf = environ['wsgi.input']
        length = int(environ.get('CONTENT_LENGTH', 0))
        query = cgi.parse_qsl(buf.read(length))

        if album_id == 'all' :
            # effect all rows...
        else :
            if photo_id = '' :
                # effect album's all photos...
            else :
                # effect id's photo id...
        
        return self.app_index(environ, start_response)  # display effected result ( or redirect)
    


#options....
parser = OptionParser(usage="%prog -d FILENAME [-p]", version="%prog 0.1")

parser.add_option('-d', '--db-file', dest='dbfile',
                  help='specify sqlite db file by output piwato --db-out option.',
                  metavar="FILENAME", default=None)

parser.add_option('-p', '--port', dest='port',
                  help='specify sqlite db file by output piwato --db-out option.',
                  metavar="PORT", default="8080")

(options, args) = parser.parse_args()

if not options.dbfile :
    parser.error("specify dbfile.\n")

if int(options.port) <= 1024 :
    paraser.error("invalid port. over 1024\n")

db = piwadb.PiwaDb(options.dbfile)
piwaform = PiwaForm(db)

server = simple_server.make_server('', int(options.port), piwaform)
server.serve_forever()
